package cn.bitkit.tools.file;

import java.util.Map;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import tools.jackson.core.type.TypeReference;
import tools.jackson.databind.DeserializationFeature;
import tools.jackson.databind.JsonNode;
import tools.jackson.databind.MapperFeature;
import tools.jackson.databind.ObjectMapper;
import tools.jackson.dataformat.xml.XmlFactory;
import tools.jackson.dataformat.xml.XmlMapper;

/**
 * @author changbo
 */
@Slf4j
public class XmlUtil{
	
	public static TypeReference<Map<String, String>> TYPE_MAP = new TypeReference<Map<String, String>>(){};

	private static XmlMapper getXmlMapper(){
		XmlMapper.Builder builder = XmlMapper.builder(new XmlFactory());
		builder.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		builder.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
		return builder.build();
	}

	@SneakyThrows
	public static <T> T parse(String xml, Class<T> clazz) {
		return getXmlMapper().readValue(xml, clazz);
	}

	@SneakyThrows
	public static <T> T parse(String xml, TypeReference<T> typeReference) {
		return getXmlMapper().readValue(xml, typeReference);
	}

	@SneakyThrows
	public static String toXml(Object obj) {
		return getXmlMapper().writeValueAsString(obj);
	}

    @SneakyThrows
    public static String toJson(String xml) {
        JsonNode jsonNode = getXmlMapper().readTree(xml);
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(jsonNode);
    }
    
}
